/**
 * 
 */
package and2.ex.api.request;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;

import android.content.Context;
import android.util.Log;

/**
 * @author sospartan
 * 
 */
public class WebReq {
	private static final String TAG = "WebReq";
	private static final String USER_AGENT = "and2ex";

	protected String request(String url, DefaultHttpClient client)
			throws Exception {
		String result = null;
		int statusCode = 0;
		HttpGet getMethod = new HttpGet(url);
		Log.d(TAG, "do the getRequest,url=" + url + "");
		try {
			getMethod.setHeader("User-Agent", USER_AGENT);

			HttpResponse httpResponse = client.execute(getMethod);
			// statusCode == 200 正常
			statusCode = httpResponse.getStatusLine().getStatusCode();
			Log.d(TAG, "statuscode = " + statusCode);
			if (statusCode == 200) {
				result = retrieveInputStream(httpResponse.getEntity());
			} else {

			}

		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
			throw new Exception(e);
		} finally {
			getMethod.abort();
		}
		return result;
	}

	protected String request(String url, DefaultHttpClient client,
			String basicStr) throws Exception {
		String result = null;
		int statusCode = 0;
		HttpGet getMethod = new HttpGet(url);
		Log.d(TAG, "do the getRequest,url=" + url + "");
		try {
			getMethod.setHeader("User-Agent", USER_AGENT);
			getMethod.addHeader("Authorization", "Basic " + basicStr);
			HttpResponse httpResponse = client.execute(getMethod);
			statusCode = httpResponse.getStatusLine().getStatusCode();
			Log.d(TAG, "statuscode = " + statusCode);
			result = retrieveInputStream(httpResponse.getEntity());
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
			throw new Exception(e);
		} finally {
			getMethod.abort();
		}
		Log.d(TAG, result);
		return result;
	}

	/**
	 * 处理httpResponse信息,返回String
	 * 
	 * @param httpEntity
	 * @return String
	 */
	protected String retrieveInputStream(HttpEntity httpEntity) {
		Long l = httpEntity.getContentLength();
		int length = (int) httpEntity.getContentLength();
		if (length < 0)
			length = 10000;
		StringBuffer stringBuffer = new StringBuffer(length);
		try {
			InputStreamReader inputStreamReader = new InputStreamReader(
					httpEntity.getContent(), HTTP.UTF_8);
			char buffer[] = new char[length];
			int count;
			while ((count = inputStreamReader.read(buffer, 0, length - 1)) > 0) {
				stringBuffer.append(buffer, 0, count);
			}
		} catch (UnsupportedEncodingException e) {
			Log.e(TAG, e.getMessage());
		} catch (IllegalStateException e) {
			Log.e(TAG, e.getMessage());
		} catch (IOException e) {
			Log.e(TAG, e.getMessage());
		}
		return stringBuffer.toString();
	}

	public static class Builder {
		private String endPoint;
		private String basicStr = null;
//		private Context context;
		private DefaultHttpClient dhc = new DefaultHttpClient();


		public Builder setAuth(String username,String passwd){
			this.basicStr = BasicAuth.encode(username, passwd);
			return this;
		}
		public Builder setEndPoint(String endPoint) {
			this.endPoint = endPoint;
			return this;
		}

		public <T>T req(String uri,Class<T> classOfT) throws Exception{
			if(basicStr==null){
				String respon = new WebReq().request(
						endPoint + uri, dhc);
				return new Gson().fromJson(respon, 	classOfT);
			}else{
				String respon = new WebReq().request(
						endPoint + uri, dhc,basicStr);
				return new Gson().fromJson(respon, 	classOfT);
			}
		}
		
		public <T>T req(String uri, Type typeOfT) throws Exception{
			if(basicStr==null){
				String respon = new WebReq().request(
						endPoint + uri, dhc);
				return new Gson().fromJson(respon, 	typeOfT);
			}else{
				String respon = new WebReq().request(
						endPoint + uri, dhc,basicStr);
				return new Gson().fromJson(respon, 	typeOfT);
			}
		}

	}
}
